package com.koron.common.core.business.print.printstandard;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.koron.bean.base.Response;
import com.koron.common.core.business.common.entity.vo.Constant;
import com.koron.common.core.business.print.bean.PrintBusinessBean;
import com.koron.common.core.business.print.bean.PrintTemplateBean;
import com.koron.common.core.util.CodeTools;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.stereotype.Service;
import org.swan.bean.MessageBean;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class PrintStandardService {

    /***
     * 返回模版字段(格式为jason) 供 打印控件调用 获取字段
     * @param sf
     * @param templateId
     * @return
     */
    @TaskAnnotation("getFields")
    private String getFields(SessionFactory sf, String templateId) {
        log.info("获取模板中所有打印字段");
        return sf.getMapper(PrintStandardMapper.class).getFieldByTemplateId(templateId);
    }

    /**
     * 返回打印业务下的所有模版
     *
     * @param sf
     * @param businessId
     * @return
     */
    @TaskAnnotation("getTemplateListByBusiness")
    private List<PrintTemplateBean> getTemplateListByBusiness(SessionFactory sf, String businessId) {
        return sf.getMapper(PrintStandardMapper.class).getTemplateListByBusiness(businessId);
    }

    /**
     * 返回模版
     *
     * @param sf
     * @param id
     * @return
     */
    @TaskAnnotation("getTemplateListById")
    private PrintTemplateBean getTemplateListById(SessionFactory sf, String id) {
        return sf.getMapper(PrintStandardMapper.class).getTemplateListById(id);
    }


    /**
     * 创建模版
     *
     * @param sf
     * @param printTemplate
     */
    @TaskAnnotation("createInitTemplate")
    private int createInitTemplate(SessionFactory sf, PrintTemplateBean printTemplate) {
        return sf.getMapper(PrintStandardMapper.class).insertInitTemplate(printTemplate);
    }

    /**
     * 更新模版
     *
     * @param sf
     * @param id
     * @param content
     */
    @TaskAnnotation("updateTemplateContent")
    private int updateTemplateContent(SessionFactory sf, String id, byte[] content) {
        return sf.getMapper(PrintStandardMapper.class).updateTemplateContent(id, content);
    }

    /**
     * 获取打印业务列表
     *
     * @param factory
     * @return
     */
    @TaskAnnotation("readPrintBusList")
    public List<PrintBusinessBean> readPrintBusList(SessionFactory factory) {
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        List<PrintBusinessBean> beanList = mapper.readPrintBusList();

//		MessageBean<List> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "获取打印业务列表", List.class);
//		msg.setData(beanList);
        return beanList;
    }

    /**
     * 添加打印业务
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("addPrintBus")
    public String addPrintBus(SessionFactory factory, PrintBusinessBean bean) {
        bean.setName(StringUtils.trim(bean.getName()));
        if (StringUtils.isBlank(bean.getName())) {
            Assert.isFalse(true, "名称不能为空");
        }
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        //验证是否有重复字段
        if (verifyRepeat(bean.getField(), "fieldCode")) {
            Assert.isFalse(true, "存在重复字段,添加失败！");
        }
        bean.setId(CodeTools.getCode32());
        bean.setDeleteFlag(0);
        mapper.addPrintBus(bean);

        return bean.getId();
    }

    /**
     * 直接打开设计模板
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("directDesign")
    public String directDesign(SessionFactory factory, PrintBusinessBean bean) {
        bean.setName(StringUtils.trim(bean.getName()));
        if (StringUtils.isBlank(bean.getName())) {
            Assert.isFalse(true, "名称不能为空");
        }
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        //验证是否有重复字段
        if (verifyRepeat(bean.getField(), "fieldCode")) {
            Assert.isFalse(true, "存在重复字段,添加失败！");
        }
        //单据id获取打印业务
        PrintBusinessBean busbean = mapper.queryFirstByBusinessCode(bean.getCode());
        //没有就新增
        if(ObjectUtil.isNull(busbean)){
            String id = addPrintBus(factory, bean);
            PrintTemplateBean templateBean = new PrintTemplateBean(bean.getName(), id,true);//每个单据只有一个模板
            return addPrintTem(factory, templateBean);
        }  else{
            bean.setId(busbean.getId());//单据业务id 换 打印业务id
            updatePrintBus(factory, bean);//如果已经存在每次调用接口都进行更新操作
            return mapper.getTemplateListByBusiness(busbean.getId()).stream().findFirst().get().getId();//获取模板id
        }
    }

    /**
     * 修改打印业务
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("updatePrintBus")
    public Response<String> updatePrintBus(SessionFactory factory, PrintBusinessBean bean) {
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        mapper.updatePrintBus(bean);

        if (bean.getDeleteFlag() != null && bean.getDeleteFlag() == 1) {
            mapper.deletePrintTemByBusId(bean.getId());
        }

        return Response.ok(bean.getId());
    }

    /**
     * 获取打印模板列表-明细
     *
     * @param factory
     * @param businessId
     * @return
     */
    @TaskAnnotation("readPrintTemList")
    public List<PrintTemplateBean> readPrintTemList(SessionFactory factory, String businessId) {
        log.info("返回业务组下所有模板");
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        List<PrintTemplateBean> beanList = mapper.getTemplateListByBusiness(businessId);

        return beanList;
    }

    /**
     * 添加打印模板
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("addPrintTem")
    public String addPrintTem(SessionFactory factory, PrintTemplateBean bean) {
        bean.setName(StringUtils.trim(bean.getName()));
        if (StringUtils.isBlank(bean.getName())) {
            Assert.isFalse(true, "模板名称不能为空，修改失败");
        }

        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        bean.setId(CodeTools.getCode32());
        bean.setDeleteFlag(0);
        mapper.insertInitTemplate(bean);

        if (bean.getDefaultFlag() != null && bean.getDefaultFlag()) {
            mapper.setDefaultPrintTem(bean.getBusinessId(), bean.getId());
        }

        return bean.getId();
    }

    /**
     * 修改打印模板
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("updatePrintTem")
    public Response<String> updatePrintTem(SessionFactory factory, PrintTemplateBean bean) {
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        mapper.updatePrintTem(bean);
        if (bean.getDefaultFlag() != null && bean.getDefaultFlag()) {
            mapper.setDefaultPrintTem(bean.getBusinessId(), bean.getId());
        }

        return Response.ok(bean.getId());
    }

    /**
     * 设置默认模板
     *
     * @param factory
     * @param bean
     * @return
     */
    @TaskAnnotation("setupDefaultTem")
    public MessageBean<String> setupDefaultTem(SessionFactory factory, PrintTemplateBean bean) {
        PrintStandardMapper mapper = factory.getMapper(PrintStandardMapper.class);
        //取消已经默认的打印模板
        mapper.setupDefaultTem();
        mapper.updatePrintTem(bean);

        MessageBean<String> msg = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "设置默认模板", String.class);
        msg.setData(bean.getId());
        return msg;
    }

    /**
     * @param json
     * @param filed
     * @return true 重复；false 不重复
     * @desc 验证是否重复
     * @author dulingjiang
     * @date 2019年7月20日
     */
    public static Boolean verifyRepeat(String json, String filed) {
        if (StringUtils.isBlank(json) || StringUtils.isBlank(filed)) {
            return false;
        }
        JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
        Set<String> set = new HashSet<String>();
        for (int i = 0, j = jsonArray.size(); i < j; i++) {
            JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
            String filedValue = jsonObject.get(filed).getAsString();
            if (!set.add(filedValue)) {
                return true;
            }
        }
        return false;
    }
}
